﻿using ACIM365.Models;
using ACIM365.Services;
using ACIM365.Views;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Xamarin.Essentials;
using Xamarin.Forms;

namespace ACIM365.ViewModels
{
    class MainViewModel : BaseViewModel
    {
        ILessonService _lessonService;
        INavigation _navigation;

        public MainViewModel(INavigation navigation)
        {
            _navigation = navigation;
            _lessonService = DependencyService.Get<ILessonService>();

            var titleIndex = Preferences.Get("CurLessonIndex", "A:1:0");
            Title = _lessonService.GetTitle(titleIndex);

            MessagingCenter.Subscribe<BaseViewModel, Lesson>(this, "SelectLesson", (sender, lesson) =>
            {
                Title = lesson;
            });
        }

        Lesson _title;
        public Lesson Title
        {
            get
            {
                return _title;
            }
            set
            {
                _title = value;

                Preferences.Set("CurLessonIndex", value.Index);

                OnPropertyChanged("Title");
                OnPropertyChanged("Contents");
            }
        }

        public ObservableCollection<Lesson> Contents
        {
            get
            {
                return new ObservableCollection<Lesson>(_lessonService.GetContent(Title.Index.Replace("A", "B")));
            }
        }

        ICommand _nextLessonCommand;
        public ICommand NextLessonCommand
        {
            get
            {
                _nextLessonCommand = _nextLessonCommand ?? new Command(execute: (o) =>
                {
                    Title = _lessonService.GetNextTitle((o as Lesson).Index);
                });
                return _nextLessonCommand;
            }
        }

        ICommand _cataLogViewCommand;
        public ICommand CataLogViewCommand
        {
            get
            {
                _cataLogViewCommand = _cataLogViewCommand ?? new Command(execute: async (o) =>
                {
                    await _navigation.PushAsync(new CatalogView(o as Lesson));
                });
                return _cataLogViewCommand;
            }
        }
    }
}
